package com.showde.shoppingmall.business.logic;

import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.kim.net.NetEntity;
import com.showde.shoppingmall.ShoppingMallApplication;
import com.showde.shoppingmall.business.LoginBusiness;
import com.showde.shoppingmall.business.NetCallbackImplBase.Notify;
import com.showde.shoppingmall.db.UserDBCommand;
import com.showde.shoppingmall.domain.User;

public class LoginLogic {

	private static final String TAG = "LoginLogic";

	// 测试账号
	// account:
	// password:

	public static void login(final Context context, String userAccount,
			String password, final UICallbackInterface uiCallbackInterface) {
		LoginBusiness business = new LoginBusiness(userAccount, password,
				new Notify() {

					@Override
					public void notifyNetCallback(NetEntity netEntity) {
						JSONObject jsonObject = netEntity.result;
						if (jsonObject == null) {
							uiCallbackInterface.onError("no data response...");
							return;
						}
						// Log.d(TAG, "responseData::" + jsonObject.toString());
						try {
							String returnCode = jsonObject
									.getString("ReturnCode");
							if ("0".equals(returnCode)) {
								JSONObject userJson = jsonObject
										.getJSONObject("User");
								User user = json2User(userJson);
								// 暂时用户id和账号一致
								user.setUserID(user.getUserAccount());
								if (user != null) {
									UserDBCommand command = new UserDBCommand(
											context);
									command.add(user);
									CallbackData callbackData = new CallbackData();
									callbackData.data = user;
									ShoppingMallApplication.userSession
											.setSession(user);
									uiCallbackInterface.onSuccess(callbackData);
									return;
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						uiCallbackInterface.onError("parseError");
					}

					@Override
					public void notifyError(int httpResponseCode,
							String errorMsg) {
						uiCallbackInterface.onError(errorMsg);
					}
				});
		business.doBusiness();
	}

	private static User json2User(JSONObject jsonObject) {
		if (jsonObject == null) {
			return null;
		}
		User user = new User();
		try {
			user.setUserAccount(jsonObject.getString("account")); // 账号
			user.setUserName(jsonObject.getString("name")); // 用户名
			user.setUserPassword(jsonObject.getString("password"));// 密码
			user.setUserEmail(jsonObject.getString("email"));// 邮箱地址
			user.setUserCardType(jsonObject.getString("cardtype")); // 证件类型
			user.setUserCardNum(jsonObject.getString("cardno")); // 证件号码
			user.setUserPhone(jsonObject.getString("phone")); // 电话
			user.setUserMobile(jsonObject.getString("mobile")); // 移动电话
			return user;
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
		return null;
	}
}